#!/usr/bin/env node
const process = require("process");
const path = require("path");
const ejs = require("ejs");
const fs = require("fs");
const inquirer = require("inquirer");
const fse = require("fs-extra");

const modelNames = fs
  .readdirSync(path.join(process.cwd(), "/src/models"))
  .map((n) => n.replace(".js", ""));

if (modelNames == undefined || modelNames.length == 0) {
  console.error("没有找到model目录的模型。请使用npm run model生成");
} else {
  // 选择参数
  const prompt = [
    {
      type: "list",
      message: "请选择需要生成代码的表",
      name: "model",
      choices: modelNames,
    },
  ];
  inquirer.prompt(prompt).then((answers) => {
    // 获取表属性
    const model = require(path.join(
      process.cwd(),
      "/src/models/" + answers.model
    )).toString();
    const reg = /field: "([^"]*?)"/g;
    const attrs = model.match(reg).map((n) =>
      n
        .replace('field: "', "")
        .replace('"', "")
        .replace(/\_(\w)/g, (all, letter) => letter.toUpperCase())
    );
    //生成代码
    let modelName = answers.model.replace(/^\S/g, (first) =>
      first.toUpperCase()
    );
    ejs.renderFile(
      __dirname + "/../template/controller.ejs",
      {
        modelName: modelName,
        modelFileName: answers.model,
        attrs: attrs,
      },
      {},
      function (err, str) {
        if (err) {
          console.error("生成出错", err);
        } else {
          const dirName = answers.model.replace(/([A-Z])/g, "-$1").toLowerCase();
          fse.ensureDirSync(path.join(process.cwd(), "src", dirName));
          fse.outputFileSync(
            path.join(
              process.cwd(),
              "src",
              dirName,
              "/" + dirName + "-controller.js"
            ),
            str
          );
          console.log("Done!");
        }
      }
    );
  });
}
